package cn.john.hrm.userdetails;

import cn.john.hrm.LoginUserConstant;
import cn.john.hrm.client.UserInfoFeignClient;
import cn.john.hrm.constant.AuthConstant;
import cn.john.hrm.domain.LoginUser;
import cn.john.hrm.domain.Permission;
import cn.john.hrm.domain.UserContextInfo;
import cn.john.hrm.mapper.LoginUserMapper;
import cn.john.hrm.util.AjaxResult;
import cn.john.hrm.util.ValidUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HrmUserDetailsService implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户是否存在
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        // 判断用户是否存在
        ValidUtils.assertNotNull(loginUser, "对不起，该用户不存在!!!");
        // 如果用户存在，则查询其对应的权限
        List<Permission> permissions = loginUserMapper.loadUserPermissionById(loginUser.getId());
        ArrayList<GrantedAuthority> authors = new ArrayList<>();
        // 遍历所有用户的权限 交给security
        permissions.stream().forEach(permission -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
            authors.add(simpleGrantedAuthority);
        });
        // 判断是否为管理员 如果是管理员 获取其它信息
        if(loginUser.getType() == LoginUserConstant.LOGIN_USER_ADMIN) {
            AjaxResult result = userInfoFeignClient.getUserInfo(loginUser.getId());
            System.out.println(result.getResultObj());
            if (!result.isSuccess())
                throw new RuntimeException(result.getMessage());
            // 获取result中的用户相关信息
            Object resultObj = result.getResultObj();
            // 判断resultObj是否为空 如果不为空则强转
            ValidUtils.assertNotNull(resultObj, "对不起，没有该管理员!!!");
            // 远程调用传递的是Json格式的数据 因此需要先转换为Json字符串
            String json = JSON.toJSONString(resultObj);
            // 将Json字符串转换为Java对象
            UserContextInfo userInfo = JSON.parseObject(json, UserContextInfo.class);
            String key = AuthConstant.USER_INFO_KEY + loginUser.getUsername();
            redisTemplate.opsForValue().set(key, userInfo);
        }
        return new User(loginUser.getUsername(),loginUser.getPassword(),authors);
    }
}
